package com.stropheware.droidDefense;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;

public class TowerManager {
	
	public ArrayList<AbstractTower> towers = new ArrayList<AbstractTower>();
	
	private GameBoard gameBoard;
	private GameManager gameManager;
	
	public TowerManager(GameManager gameManager) {
		this.gameBoard = gameManager.gameBoard;
		this.gameManager = gameManager;
	}
	
	public void addTower(Cell topLeftCell, AbstractTower tower) {
		towers.add(tower);
		gameBoard.addTowerGameBoard(topLeftCell, towers.get(towers.size()-1));
		gameManager.towerBought(tower.cost);
	}
	
	public void removeTower(Cell topLeftCell, AbstractTower tower) {
		towers.remove(tower);
		gameBoard.removeTowerGameBoard(topLeftCell);
	}
	
	public void update(int tickCount) {
		for(int i = 0; i < towers.size(); i++) {
			towers.get(i).update(tickCount);
		}
	}
	
	public void evaluateTargets() {
		AbstractEnemy [] temp = gameManager.enemyManager.getActiveEnemyArray();
		for(int i = 0; i < towers.size(); i++) {
			towers.get(i).analyzePotentialEnemies(temp);
		}
	}
	
	public boolean isValidPlacement(Cell topLeft, Cell bottomRight, Cell topRight, Cell bottomLeft) {
		for(int i = 0; i < towers.size(); i++) {
			Cell towerTopLeft = towers.get(i).cellsOccupied[0][0];
			if((topLeft.getColumn() >= towerTopLeft.getColumn() && topLeft.getColumn() < towerTopLeft.getColumn() + AbstractTower.TOWER_SIDE_LENGTH) &&
					(topLeft.getRow() >= towerTopLeft.getRow() && topLeft.getRow() < towerTopLeft.getRow() + AbstractTower.TOWER_SIDE_LENGTH) || 
					(bottomRight.getColumn() >= towerTopLeft.getColumn() && bottomRight.getColumn() < towerTopLeft.getColumn() + AbstractTower.TOWER_SIDE_LENGTH) &&
					(bottomRight.getRow() >= towerTopLeft.getRow() && bottomRight.getRow() < towerTopLeft.getRow() + AbstractTower.TOWER_SIDE_LENGTH) ||
					(topRight.getColumn() >= towerTopLeft.getColumn() && topRight.getColumn() < towerTopLeft.getColumn() + AbstractTower.TOWER_SIDE_LENGTH) &&
					(topRight.getRow() >= towerTopLeft.getRow() && topRight.getRow() < towerTopLeft.getRow() + AbstractTower.TOWER_SIDE_LENGTH) ||
					(bottomLeft.getColumn() >= towerTopLeft.getColumn() && bottomLeft.getColumn() < towerTopLeft.getColumn() + AbstractTower.TOWER_SIDE_LENGTH) &&
					(bottomLeft.getRow() >= towerTopLeft.getRow() && bottomLeft.getRow() < towerTopLeft.getRow() + AbstractTower.TOWER_SIDE_LENGTH)) return false;
		}
		return true;
	}
	
	public void drawTowers(Canvas canvas){
		for(int i = 0; i < towers.size(); i++)towers.get(i).drawDrawable(canvas);
	}
	
	public void drawProjectiles(Canvas canvas) {
		for(int i = 0; i < towers.size(); i++)towers.get(i).drawProjectiles(canvas);
	}
	
	public void roundCompleted() {
		for(int i = 0; i < towers.size(); i++)towers.get(i).roundCompleted();
	}
}
